package org.example.controller;

import io.github.resilience4j.retry.annotation.Retry;
import io.github.resilience4j.timelimiter.annotation.TimeLimiter;
import org.example.service.TestService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;

@RestController
@RequestMapping("/test1")

public class TestController {

    private static final Logger logger= LoggerFactory.getLogger(TestController.class);
    static final String URL="http://eureka-client";
//    static final String URL="http://localhost:8001";

    @Autowired
    private RestTemplate restTemplate;

    @Resource
    private TestService testService;

//    public Resil

    @GetMapping("/hello")
    public String hello(){
//        String result=restTemplate.getForObject(URL+"/hello",String.class);
        String result=testService.hello();
//        System.out.println(result);
        logger.info(result);
        return result;
    }

    @GetMapping("/world")
    public String world(){
//        String result=restTemplate.getForObject(URL+"/world",String.class);
        String result=testService.world();
//        System.out.println(result);
        logger.info(result);
        return result;
    }

    @GetMapping("/timeout")
    @TimeLimiter(name = "delay", fallbackMethod = "timeoutfallback")
    public CompletableFuture<String> timeout(){
        logger.info("进入方法：{}",System.currentTimeMillis());
//        String result=testService.timeout();
        CompletableFuture<String> result = CompletableFuture.supplyAsync((Supplier<String>)() -> testService.timeout());
        logger.info("离开方法：{}",System.currentTimeMillis());
        return result;
    }

    public CompletableFuture<ResponseEntity> timeoutfallback(Exception e){
        logger.info("调用失败：{}",System.currentTimeMillis());
        e.printStackTrace();
        return CompletableFuture.completedFuture(ResponseEntity.ok("读取超时123"));
    }


    @GetMapping("/retry")
    @Retry(name = "backendB")
    public String retry() {
        logger.info("*********进入方法*********");
        //异步操作
        if(Math.random()>0.5){
            throw new RuntimeException("测试");
        }
//        CompletableFuture<String> timeout = CompletableFuture.supplyAsync(()-> testService.world());
        logger.info("*********离开方法*********");
        return "1";
    }
}
